package com.itic.appbase.applications.sys.org.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.applications.sys.common.service.InnerCommonService;
import com.itic.appbase.applications.sys.org.persistence.model.Org;
import com.itic.appbase.applications.sys.org.service.OrgService;
import com.itic.appbase.applications.sys.org.vo.OrgVo;
import com.itic.appbase.applications.sys.region.persistence.model.Region;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.InitConst;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.exception.definition.ParameterErrorException;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.ValueHelper;

/**
 * 组织机构管理
 * <p>
 * Company: itic
 * </p>
 * 
 * @author: xujing
 * @date: 2015年6月1日 上午10:31:06
 * @version: V1.0
 */
@Controller
@RequestMapping(value = "/sys/org")
public class OrgController
        extends BaseController {
    @Autowired
    private OrgService orgService;
    @Autowired
    private InnerCommonService innerCommonService;

    private static final Map<String, String> codeMap = new HashMap<String, String>();

    static {
        codeMap.put("type", "T_DM_ORG_TYPE"); // 机关类型代码表
        codeMap.put("clazz", "T_DM_ORG_CLAZZ"); // 机构类别代码表
    }

    /**
     * 跳转到主页面
     * 
     * @return
     */
    @RequestMapping(value = "/init")
    public String init() {
        return "sys/org/orgMain";
    }

    /**
     * 跳转到新建页面
     * 
     * @param id
     *            主键id
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/initAdd")
    public String initAdd(String id, Model model) {
        if (StringHelper.isNotBlank(id)) {
            Org parentOrg = orgService.get(id);
            model.addAttribute("parentOrg", parentOrg);
        } else {
            throw new ParameterErrorException();
        }

        return "sys/org/orgAdd";
    }

    /**
     * 跳转到编辑页面
     * 
     * @param id
     *            主键id
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/initEdit")
    public String initEdit(String id, Model model) {
        if (StringHelper.isNotBlank(id)) {
            Org record = orgService.get(id);
            if (null != record) {
                OrgVo orgVo = new OrgVo();
                ValueHelper.model2vo(record, orgVo);

                // 获取上级机构名称
                if (StringHelper.isNoneBlank(record.getpCode()) && !InitConst.P_CODE.equals(record.getpCode())) {
                    Org parentOrg = orgService.selectOrgByCode(record.getpCode());
                    String pName = parentOrg != null && StringHelper.isNotBlank(parentOrg.getName()) ? parentOrg
                            .getName() : "";
                    orgVo.setpName(pName);
                }

                model.addAttribute("orgData", iticJsonMapper.toJson(orgVo));
                model.addAttribute("orgVo", orgVo);
            }
        } else {
            throw new ParameterErrorException();
        }

        return "sys/org/orgEdit";
    }

    /**
     * 跳转到查看页面
     * 
     * @param id
     *            主键id
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/initView")
    public String initView(String id, Model model) {
        if (StringHelper.isNotBlank(id)) {
            Org record = orgService.get(id);
            if (null != record) {
                OrgVo orgVo = new OrgVo();
                ValueHelper.model2vo(record, orgVo);

                // 获取上级机构名称
                if (StringHelper.isNoneBlank(record.getpCode()) && !InitConst.P_CODE.equals(record.getpCode())) {
                    Org parentOrg = orgService.selectOrgByCode(record.getpCode());
                    String pName = parentOrg != null && StringHelper.isNotBlank(parentOrg.getName()) ? parentOrg
                            .getName() : "";
                    orgVo.setpName(pName);
                }

                // 行政区划
                Region region = innerCommonService.getRegionById(record.getRegionId());
                String regionName = (null != region && StringHelper.isNotBlank(region.getName())) ? region.getName()
                        : "";
                orgVo.setRegionName(regionName);

                // 代码转名称
                record = (Org) innerCommonService.getNameByCode(record, codeMap);
                orgVo.setTypeName(record.getType());
                orgVo.setClazzName(record.getClazz());

                model.addAttribute("org", orgVo);
            }
        } else {
            throw new ParameterErrorException();
        }

        return "sys/org/orgView";
    }

    /**
     * 查询树list
     * 
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Map<String, Object> getOrgList(HttpServletRequest request) {
        // 获取前台传递pCode参数，用于显示树结构，不传时，默认显示pCode=-1的整棵树
        String pCode = this.getCleanParams(request, "pCode");
        pCode = StringHelper.isBlank(pCode) ? InitConst.P_CODE : pCode;
        // 封装查询条件
        Org queryOrg = new Org();
        queryOrg.setIsEffective(DBConst.TRUE);
        queryOrg.setpCode(pCode);

        List<Org> orgList = orgService.selectOrgList(queryOrg);

        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
        resultMap.put(IticConst.DATA, orgList);
        return resultMap;
    }

    /**
     * 根据pCode异步加载树节点（异步刷新）
     * 
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/getTree")
    @ResponseBody
    public List<Org> getTree(HttpServletRequest request) {
        // 获取前台传递pCode参数，用于显示树结构，不传时，默认显示pCode=-1的整棵树
        String pCode = this.getCleanParams(request, "pCode");
        pCode = StringHelper.isBlank(pCode) ? InitConst.P_CODE : pCode;
        // 封装查询条件
        Org queryOrg = new Org();
        queryOrg.setIsEffective(DBConst.TRUE);
        queryOrg.setpCode(pCode);
        return orgService.selectOrgList(queryOrg);
    }

    /**
     * 保存操作
     * 
     * @param request
     * @param response
     * @param org
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Map<String, String> add(HttpServletRequest request, Org org) {
        Map<String, String> resultMap = new HashMap<String, String>();
        String result = ResponseCode.SERVER_ERROR.getCode();

        // 获取父级组织机构代码
        String orgCode = this.getCleanParams(request, "regionCode");

        if (null != org && StringHelper.isNotBlank(orgCode)) {
            org.setCode(orgCode + IdGen.randomInt8());
            result = orgService.add(org);
        } else {
            result = ResponseCode.PARAM_INVALID.getCode();
        }

        resultMap.put(IticConst.RESULT, result);
        return resultMap;
    }

    /**
     * 编辑操作
     * 
     * @param request
     * @param org
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/edit")
    @ResponseBody
    public Map<String, String> edit(Org org) {
        Map<String, String> resultMap = new HashMap<String, String>();
        String result = ResponseCode.SERVER_ERROR.getCode();

        if (null != org && StringHelper.isNotBlank(org.getId())) {
            result = orgService.edit(org);
        } else {
            result = ResponseCode.PARAM_INVALID.getCode();
        }

        resultMap.put(IticConst.RESULT, result);
        return resultMap;
    }

    /**
     * 删除操作
     * 
     * @param request
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Map<String, String> delete(String id) {
        Map<String, String> resultMap = new HashMap<String, String>();
        String result = ResponseCode.SERVER_ERROR.getCode();

        if (StringHelper.isNotBlank(id)) {
            result = orgService.deleteOrgTree(id);
        } else {
            result = ResponseCode.PARAM_INVALID.getCode();
        }

        resultMap.put(IticConst.RESULT, result);
        return resultMap;
    }
}